import React from 'react'
import { messages, queryCurrencyPrecision } from 'share/common'
import {Form, Button, Input, Row, Col, message, Modal} from 'antd'
const FormItem = Form.Item;
const {TextArea} = Input;
import backlashService from './pay-backlash-recheck.service'
import menuRoute from 'routes/menuRoute'
import ApproveHistory from "containers/pay/payment-backlash/approve-history-work-flow"
import {Alert} from 'antd';
import PayDetail from 'containers/pay/pay-workbench/payment-detail' //支付详情
import Upload from 'components/upload-button';

class PayResverCheckDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      queryFlag: true,
      draweeAccountNumber: [],
      payeeAccountNumber: [],
      currencyList: [],//币种
      data: {},
      abledRefundAmount: 0,
      showDetail: false,
      detailFlag: '',
      documentInfo: {},
      sourceDetail: {},
      backlashDetail: {},
      backlashFlag: false,
      detailId: undefined,
      saveData: {},//保存后返回新的支付数据
      saveFlag: false,//是否已经保存
      btnLoading: false,//按钮加载
      showButtonFlag: true,
      showChild: false,
      historyLoading: true,
      modalVisible: false,
      passModalVisible: false,
      rejectRemark: {},
      uploadOIDs: [], //上传附件的OIDs
      fileList: [],
      fileShow: false,
    }
  }

  componentWillReceiveProps(nextProps) {
    const record = nextProps.params.record;
    if (record && this.state.queryFlag && nextProps.params.flag) {//查询
      this.setState({formLoading: true});
      backlashService.getBacklashDTOBybacklashDetailId(record.backDetail.id).then(
        res => {
          if (res.status === 200) {
            let data = res.data || {};
            let documentInfo = data.payDocumentDTO;
            let sourceDetail = data.detail;
            let backlashDetail = data.backDetail;
            let fileList = [];
            if (backlashDetail.backlashAttachments) {
              backlashDetail.backlashAttachments.map(item => {
                fileList.push({
                  ...item,
                  uid: item.id,
                  name: item.fileName,
                  status: "done"
                })
              })
            }
            if (backlashDetail) {
              if (backlashDetail.paymentStatus === "N") {//如果是编辑中，则可以发起反冲
                this.setState({
                  queryFlag: false,
                  data: data,
                  documentInfo: documentInfo,
                  sourceDetail: sourceDetail,
                  backDetail: backlashDetail,
                  showDetail: true,
                  fileShow: true,
                  uploadOIDs: backlashDetail.backlashAttachmentOID,
                  fileList: fileList,
                });
              } else {//其他状态则隐藏下部4个按钮
                this.setState({
                  queryFlag: false,
                  data: data,
                  documentInfo: documentInfo,
                  sourceDetail: sourceDetail,
                  backlashDetail: backlashDetail,
                  showDetail: true,
                  showButtonFlag: false,
                  uploadOIDs: backlashDetail.backlashAttachmentOID,
                  fileList: fileList,
                });
              }
            } else {
              this.setState({
                queryFlag: false,
                data: data,
                documentInfo: documentInfo,
                sourceDetail: sourceDetail,
              });
            }
            this.getApproveHistory();
          }
        }
      ).catch(() => {
        this.setState({ queryFlag: false });
        message.error(messages('pay.key210')/*获取支付明细数据失败！获取支付明细数据失败！*/);
      });
    }
    if (this.props.params.flag && !nextProps.params.flag) {
      this.setState({
        queryFlag: true,
        draweeAccountNumber: [],
        payeeAccountNumber: [],
        saveFlag: false
      });
      this.props.form.resetFields();
    }
  }

  //上传附件
  handleUpload = (OIDs) => {
    this.setState({uploadOIDs: OIDs})
  };

  //通过
  handleApprovePass = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.onCancel();
        const {id} = this.state.backlashDetail;
        this.setState({loading: true});
        let remark = values['backlashRemarks'];
        let params = values['passDesc'];
        if (!params) {
          params = " ";
        }
        backlashService.updateBacklashStatusByDetailId(id, params, "S", remark).then(res => {
          if (res.status === 200) {
            message.success(messages('pay.key211')/*复核成功*/);
            this.setState({
              loading: false,
              passModalVisible: false
            });
            this.onCancel()
          }
        }).catch(e => {
          this.setState({
            loading: false,
            passModalVisible: false
          });
          message.error(`${e.response.data.message}`)
        })
      }
    });
  };


  //不通过
  handleApproveReject = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.onCancel();
        const {id} = this.state.backlashDetail;
        let params = values['desc'];
        let remark = values['backlashRemarks'];
        if (!params) {
          params = " ";
        }
        backlashService.updateBacklashStatusByDetailId(id, params, "F", remark).then(res => {
          if (res.status === 200) {
            message.success(messages('pay.key212')/*驳回成功*/);
            this.setState({
              loading: false,
              modalVisible: false
            });
          }
        }).catch(e => {
          this.setState({
            loading: false,
            modalVisible: false
          });
          message.error(`${e.response.data.message}`)
        })
      }
    });
  };

  onCancel = () => {
    this.props.close();
    this.props.form.resetFields();
    this.setState({
      showButtonFlag: true,
      showDetail: false
    })
  };


  //查看支付流水详情
  viewPayDetail = (id) => {
    this.setState({
      showChild: true,
      detailId: id,
      detailFlag: 'PAYDETAIL'
    })
  };

  //查看单据详情
  viewDocumentDetail = (id) => {
    this.setState({
      showChild: true,
      detailId: id,
      detailFlag: 'DECUMENT'
    })
  };

  //弹出框关闭
  onClose = () => {
    this.setState({ showChild: false });
  };

  //点击提交
  onSubmit = () => {
    Modal.confirm({
      title: messages('pay.key194')/*确认反冲吗?*/,
      content: messages('pay.key195')/*反冲后需要进行复核!*/,
      okText: messages('common.ok')/*确定*/,
      cancelText: messages('common.cancel')/*取消*/,
      onOk: () => {
        let backDetail = this.state.backDetail;
        let backDetailId = backDetail.id;
        backlashService.submitBacklash(backDetailId).then(
          res => {
            if (res.status === 200) {
              //提交成功后进入反冲查询页面，暂时不跳
              message.success(messages('pay.key196')/*提交成功*/);
              payCanBacklash: menuRoute.getRouteItem('main-pay-backlash', 'key')    //发起反冲页面
            }
          }
        )
      },
      onCancel() {},
    });
  };

  getApproveHistory = () => {
    this.setState({
      historyLoading: true
    });
    let id = this.state.backlashDetail.id;
    backlashService.getBacklashHistory(id).then(res => {
      this.setState({historyLoading: false}, () => {
        this.setState({approveHistory: res.data})
      })
    }).catch(() => {
      message.error(messages('pay.key192')/*反冲历史加载失败，请重试*/);
      this.setState({historyLoading: false});
    })
  };

  //驳回
  onReject = () => {
    this.setState({
      modalVisible: true
    });
  };

  //通过
  onPass = () => {
    this.setState({
      passModalVisible: true
    });
  };

  /**
   * 组装方法
   * @param content 内部组件
   * @return {*} 给组件添加this.props.close(params)方法,params为返回到最外层的值
   *             同时添加外部传入的props为内部组件可用
   */
  wrapClose = (content) => {
    let id = this.state.detailId;
    const newProps = {
      params: {id: id, refund: true}
    };
    return React.createElement(content, Object.assign({}, newProps.params, newProps));
  };

  //点击删除
  onDelete = () => {
    Modal.confirm({
      title: messages('pay.key197')/*确认删除这条数据?*/,
      content: messages('pay.key198')/*删除后可以重新添加反冲信息!*/,
      okText: messages('common.ok')/*确定*/,
      cancelText: messages('common.cancel')/*取消*/,
      onOk: () => {
        let backDetail = this.state.backDetail;
        loading: true
        let backDetailId = backDetail.id;
        backlashService.deleteBacklashDetailById(backDetailId).then(
          response => {
            if (response.status === 200) {
              message.success(messages('common.delete.successful')/*删除成功*/);
              //删除成功以后回到发起反冲页面
              this.setState({
                showDetail: false
              }).catch(() => {
                this.setState({
                  loading: false,
                });
                message.error(messages('pay.key213')/*删除失败*/);
              });
              let detail = this.state.detail;
              let detailId = detail.id;
              backlashService.getReadyByDetailId(detailId).then(
                res => {
                  if (res.status === 200) {
                    loading:false
                    let data = res.data || {};
                    let documentInfo = data.payDocumentDTO;
                    let sourceDetail = data.detail;
                    this.setState({
                      queryFlag: false,
                      data: data,
                      documentInfo: documentInfo,
                      sourceDetail: sourceDetail
                    });
                  }
                }
              ).catch(() => {
                this.setState({ queryFlag: false });
                message.error(messages('pay.key191')/*获取支付明细数据失败！*/);
              });
            }
          }
        );
      },
      onCancel() {},
    });
  };

  render() {
    const {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 14, offset: 1},
    };
    const {documentInfo, sourceDetail, fileList, detailFlag, showChild, backlashDetail, showDetail, modalVisible, passModalVisible} = this.state;
    return (
      <div className="new-payment-requisition-line">
        <Alert message={messages('pay.key178')/*复核中*/}
               description={messages('pay.key199')/*等待财务确认*/}
               type="warning"
               showIcon/>
        <Form>
          <div className="common-item-title">{messages('pay.key201')/*业务单据信息*/}</div>
          <Row>
            <Col span={10} offset={1}>
              <FormItem label={messages('pay.key104')/*单据编号*/}>
                <span className="ant-form-text"><a onClick={() => {
                  this.viewDocumentDetail(documentInfo.documentId)
                }}>{documentInfo.documentCode}</a></span>
              </FormItem>
            </Col>
            <Col span={10} offset={1}>
              <FormItem label={messages('pay.key105')/*单据类型*/}>
                <span className="ant-form-text">{documentInfo.documentTypeName}</span>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={10} offset={1}>
              <FormItem label={messages('common.submit.date')/*提交日期*/}>
                <span className="ant-form-text">{(String)(documentInfo.documentDate).substr(0, 10)}</span>
              </FormItem>
            </Col>
            <Col span={10} offset={1}>
              <FormItem label={messages('pay.key15')/*申请人*/}>
                <span className="ant-form-text">{documentInfo.documentApplicant}</span>
              </FormItem>
            </Col>
          </Row>
          <div className="common-item-title">{messages('pay.key202')/*原支付信息*/}</div>
          <Row>
            <Col span={10} offset={1}>
              <FormItem label={messages('pay.key182')/*原付款流水号*/}>
                                <span className="ant-form-text"><a onClick={() => {
                                  this.viewPayDetail(sourceDetail.id)
                                }}>{sourceDetail.billcode}</a>
                                </span>
              </FormItem>
            </Col>
            <Col span={10} offset={1}>
              <FormItem label={messages('pay.key101')/*付款日期*/}>
                <span className="ant-form-text">{(String)(sourceDetail.payDate).substr(0, 10)}</span>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={10} offset={1}>
              <FormItem label={messages('pay.key107')/*付款金额*/}>
                <span className="ant-form-text">{sourceDetail.currency} {this.filterMoney(sourceDetail.amount, queryCurrencyPrecision(sourceDetail.currency), true)}</span>
              </FormItem>
            </Col>
            <Col span={10} offset={1}>
              <FormItem label={messages('common.currency.rate')/*汇率*/}>
                <span className="ant-form-text">{sourceDetail.exchangeRate}</span>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={10} offset={1}>
              <FormItem label={messages('pay.key173')/*收款方名称*/}>
                <span className="ant-form-text">{sourceDetail.partnerName}</span>
              </FormItem>
            </Col>
            <Col span={10} offset={1}>
              <FormItem label={messages('pay.key27')/*收款方账号*/}>
                <span className="ant-form-text">{sourceDetail.payeeAccountNumber}</span>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={10} offset={1}>
              <FormItem label={messages('pay.key203')/*收款方户名*/}>
                <span className="ant-form-text">{sourceDetail.payeeAccountName}</span>
              </FormItem>
            </Col>
            <Col span={10} offset={1}>
              <FormItem label={messages('pay.key204')/*付款方账号*/}>
                <span className="ant-form-text">{sourceDetail.draweeAccountNumber}</span>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={10} offset={1}>
              <FormItem label={messages('pay.key205')/*付款方户名*/}>
                <span className="ant-form-text">{sourceDetail.draweeAccountName}</span>
              </FormItem>
            </Col>
            <Col span={10} offset={1}>
              <FormItem label={messages('pay.key25')/*付款方式*/}>
                <span className="ant-form-text">{sourceDetail.paymentTypeName}</span>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={20} offset={1}>
              <FormItem label={messages('common.remark')/*备注*/}>
                <span className="ant-form-text">{sourceDetail.remark}</span>
              </FormItem>
            </Col>
          </Row>
          {
            showDetail && <div>
              <div className="common-item-title">{messages('pay.key206')/*反冲信息*/}</div>
              <Row>
                <Col span={10} offset={1}>
                  <FormItem label={messages('pay.key181')/*反冲付款流水号*/}>
                    <span className="ant-form-text">
                      <a onClick={() => this.viewPayDetail(backlashDetail.id)}>{backlashDetail.billcode}</a>
                    </span>
                  </FormItem>
                </Col>
                <Col span={10} offset={1}>
                  <FormItem label={messages('pay.key101')/*付款日期*/}>
                    <span className="ant-form-text">{(String)(backlashDetail.payDate).substr(0, 10)}</span>
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={10} offset={1}>
                  <FormItem label={messages('common.amount')/*金额*/}>
                    <span className="ant-form-text">{backlashDetail.currency} {this.filterMoney(backlashDetail.amount, queryCurrencyPrecision(backlashDetail.currency), true)}</span>
                  </FormItem>
                </Col>
                <Col span={10} offset={1}>
                  <FormItem label={messages('common.currency.rate')/*汇率*/}>
                    <span className="ant-form-text">{backlashDetail.exchangeRate}</span>
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={10} offset={1}>
                  <FormItem label={messages('pay.key173')/*收款方名称*/}>
                    <span className="ant-form-text">{backlashDetail.partnerName}</span>
                  </FormItem>
                </Col>
                <Col span={10} offset={1}>
                  <FormItem label={messages('pay.key27')/*收款方账号*/}>
                    <span className="ant-form-text">{backlashDetail.payeeAccountNumber}</span>
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={10} offset={1}>
                  <FormItem label={messages('pay.key203')/*收款方户名*/}>
                    <span className="ant-form-text">{backlashDetail.payeeAccountName}</span>
                  </FormItem>
                </Col>
                <Col span={10} offset={1}>
                  <FormItem label={messages('pay.key204')/*付款方账号*/}>
                    <span className="ant-form-text">{backlashDetail.draweeAccountNumber}</span>
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={10} offset={1}>
                  <FormItem label={messages('pay.key205')/*付款方户名*/}>
                    <span className="ant-form-text">{backlashDetail.draweeAccountName}</span>
                  </FormItem>
                </Col>
                <Col span={10} offset={1}>
                  <FormItem label={messages('pay.key25')/*付款方式*/}>
                    <span className="ant-form-text">{backlashDetail.paymentTypeName}</span>
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={10} offset={1}>
                  <FormItem label={messages('common.remark')/*备注*/}>
                    {getFieldDecorator('backlashRemarks', {
                      initialValue: backlashDetail.remark
                    })(
                      <TextArea autosize={{minRows: 2}} style={{minWidth: '100%'}}
                                placeholder={messages('common.please.input')/*请输入*/}/>
                    )}
                  </FormItem>
                </Col>
                {/*<Col span={12} offset={0}>*/}
                  {/*<Upload attachmentType="PAYMENT"*/}
                          {/*fileNum={99}*/}
                          {/*multiple={true}*/}
                          {/*disabled={true}*/}
                          {/*defaultOIDs={this.state.uploadOIDs}*/}
                          {/*uploadHandle={this.handleUpload}*/}
                          {/*defaultFileList={fileList}*/}
                  {/*/>*/}
                {/*</Col>*/}
              </Row>
            </div>}

          <div style={{padding: 20, paddingBottom: 70}}>
            <ApproveHistory loading={this.state.historyLoading} infoData={this.state.approveHistory}></ApproveHistory>
          </div>
          <div className="slide-footer">
            <Button onClick={this.onPass} type="primary">{messages('pay.key179')/*复核通过*/}</Button>
            <Button onClick={this.onReject}
                    style={{color: '#fff', background: '#f04134'}}>{messages('pay.key180')/*复核驳回*/}</Button>
            <Button onClick={this.onCancel}>{messages('common.back')/*返回*/}</Button>
          </div>
        </Form>
        <Modal title={messages('pay.key214')/*请输入原因*/}
               visible={modalVisible}
               okText={messages('pay.key180')/*复核驳回*/}
               bodyStyle={{maxHeight: '70vh', overflow: 'auto'}}
               onOk={this.handleApproveReject}
               onCancel={() => this.setState({modalVisible: false})}>
          <Form>
            <div style={{marginBottom: 15}}>{messages('pay.key214')/*请输入原因*/}</div>
            <FormItem {...formItemLayout} lable={messages('pay.key215')/*原因*/}>
              {getFieldDecorator('desc', {
                rules: [{
                  required: modalVisible ? true : false,
                  message: messages('pay.key214')/*请输入原因*/
                }]
              })(
                <TextArea autosize={{minRows: 2}} style={{minWidth: '100%'}}
                          placeholder={messages('common.please.input')/*请输入*/}/>
              )}
            </FormItem>
          </Form>
        </Modal>
        <Modal title={messages('pay.key214')/*请输入原因*/}
               visible={passModalVisible}
               okText={messages('pay.key179')/*复核通过*/}
               bodyStyle={{maxHeight: '70vh', overflow: 'auto'}}
               onOk={this.handleApprovePass}
               onCancel={() => this.setState({passModalVisible: false})}>
          <Form>
            <div style={{marginBottom: 15}}>{messages('pay.key214')/*请输入原因*/}</div>
            <FormItem {...formItemLayout} label={messages('pay.key215')/*原因*/}>
              {getFieldDecorator('passDesc')(
                <TextArea autosize={{minRows: 2}} style={{minWidth: '100%'}}
                          placeholder={messages('common.please.input')/*请输入*/}/>
              )}
            </FormItem>
          </Form>
        </Modal>
        <Modal visible={showChild}
               footer={[
                 <Button key="back" size="large"
                         onClick={this.onClose}>{messages('common.back')/*返回*/}</Button>
               ]}
               width={1200}
               closable={false}
               onCancel={this.onClose}>
          <div>
            {this.wrapClose(PayDetail)}
          </div>
        </Modal>
      </div>

    )
  }
}


PayResverCheckDetail.contextTypes = {
  router: React.PropTypes.object
};

const wrappedPayResverCheckDetail = Form.create()(PayResverCheckDetail);

export default wrappedPayResverCheckDetail;
